package cn.laixueit.controller;

import cn.laixueit.pojo.Users;
import cn.laixueit.service.UserService;
import cn.laixueit.utils.EmailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Scope("prototype")
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping("/sendmail")
    public  boolean sendmail(String email, HttpSession session){
        try {
            String code = EmailUtils.sendEmail(email);
            session.setAttribute("code",code);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @RequestMapping("/addUser")
    public boolean addUser(Users users,String code,HttpSession session){
        Object sessionCode = session.getAttribute("code");
        if(code.equals(sessionCode)){
            String md5Pwd = DigestUtils.md5DigestAsHex(users.getPassword().getBytes());
            users.setPassword(md5Pwd);
            userService.saveUser(users);
            session.removeAttribute("code");
            return true;
        }
        return false;
    }

    @PostMapping("/login")
    public boolean login(Users users,HttpSession session){
        int i = userService.login(users);
        if(i>0){
            session.setAttribute("user",users);
            return true;
        }
        return false;
    }

    @RequestMapping("/logout")
    public boolean logout(HttpSession session){
        session.removeAttribute("user");
        return true;
    }
}
